<?php
namespace app\api\services;

use app\common\libs\Singleton;
use app\common\models\Sys\Adv;
use app\common\models\Sys\AdvImg;
use app\common\models\Sys\Area;
use app\common\models\Sys\Article;
use app\common\models\Sys\Nav;
use app\common\models\Sys\Notice;
use app\common\models\Sys\SystemConfig;
use app\common\models\Sys\Tool;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class SysService
{
    use Singleton;

    /**
     * @param $articleId
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function article($articleId): array
    {
        $where = [
            ['id', '=', $articleId],
            ['deleted', '=', 0],
            ['status', '=', 1],
        ];
        $info = Article::getInstance()->where($where)->field('title,content')->find();
        return empty($info) ? [] : $info->toArray();
    }

    public function getArticle($key): array
    {
        $where = [
            ['key', '=', $key],
            ['deleted', '=', 0],
            ['status', '=', 1],
        ];
        $info = Article::getInstance()->where($where)->field('title,content')->find();
        return empty($info) ? [] : $info->toArray();
    }

    public function advImg($type): array
    {
        $where = [
            ['type', '=', $type],
            ['deleted', '=', 0],
            ['status', '=', 1],
        ];
        $area = AdvImg::getInstance()->where($where)->field('id,img_url,title,link')->select();
        //        if(!empty($adv)){
        //            $adv['imgUrl'] = UrlConst::IMG_URL.$adv['imgUrl'];
        //        }
        return empty($area) ? [] : $area->toArray();
    }

    public function areaCity($page, $pageSize, $letter, $name): array
    {
        $where = [
            ['type', '=', 2],
        ];
        if ( ! empty($letter)) {
            $where[] = ['letter', '=', $letter];
        }
        if ( ! empty($name)) {
            $where[] = ['name', 'like', '%' . $name . '%'];
        }
        $area = Area::getInstance()->where($where)->order('letter asc')->field('this_id,name,type,letter')->select();
        $area = empty($area) ? [] : $area->toArray();
        $list = [];
        foreach ($area as $val) {
            $list[$val['letter']][] = $val;
        }

        return $list;
    }
    public function hotArea(): array
    {
        $where = [
            'is_hot' => 1,
        ];
        $area = Area::getInstance()->where($where)->field('this_id,name,type')->select();
        return empty($area) ? [] : $area->toArray();
    }

    public function area($pId): array
    {
        $where = [
            'p_id' => $pId,
        ];
        $area = Area::getInstance()->where($where)->field('this_id,name,type')->select();
        return empty($area) ? [] : $area->toArray();
    }

    public function getNotice(): array
    {
        $notice = Notice::getInstance()->where(['status' => 1, 'deleted' => 0, 'shop_id' => 0])->order('is_dialog desc,is_top desc,create_at desc')->find();
        return !empty($notice) ? $notice->toArray() : [];
    }

    public function getNav(): array
    {
        return Nav::getInstance()->where(['status' => 1, 'deleted' => 0])->order('sort desc')->field('id,link,title,img_url')->select()->toArray();
    }

    public function getTool(): array
    {
        return Tool::getInstance()->where(['status' => 1, 'deleted' => 0])->order('sort desc')->field('id,link,title,img_url')->select()->toArray();
    }

    /**
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getAdv(): array
    {
        return Adv::getInstance()->where(['status' => 1, 'deleted' => 0])->order('sort desc')->field('id,link,title,img_url')->select()->toArray();
    }

    /**
     * 解析缓存名称
     * @param string $rule 配置名称
     * @return array
     */
    private static function _parse(string $rule): array
    {
        $type = 'base';
        if (stripos($rule, '.') !== false) {
            [$type, $rule] = explode('.', $rule, 2);
        }
        [$field, $outer] = explode('|', "{$rule}|");
        return [$type, $field, strtolower($outer)];
    }

    /**
     * 设置配置数据
     * @param string $name 配置名称
     * @param mixed $value 配置内容
     * @return integer|string
     * @throws \think\admin\Exception
     */
    public static function set(string $name, $value = '')
    {
        [$type, $field] = static::_parse($name);
        if (is_array($value)) {
            $count = 0;
            foreach ($value as $kk => $vv) {
                $count += static::set("{$field}.{$kk}", $vv);
            }
            return $count;
        } else {
            try {
                $map  = ['type' => $type, 'name' => $field];
                $data = array_merge($map, ['value' => $value]);
                SystemConfig::mk()->master()->where($map)->findOrEmpty()->save($data);
                sysvar('think-library-config', []);
                Library::$sapp->cache->delete('SystemConfig');
                return 1;
            } catch (\Exception $exception) {
                throw new Exception($exception->getMessage(), $exception->getCode());
            }
        }

    }

    /**
     * 读取配置数据
     * @param string $name
     * @param string $default
     * @return array|mixed|string
     * @throws \think\admin\Exception
     */
    public static function get(string $name = '', string $default = '')
    {
        try {
            if (empty($config = sysvar('think-library-config') ?: [])) {
                SystemConfig::cache('SystemConfig')->select()->map(function ($item) use (&$config) {
                    $config[$item['type']][$item['name']] = $item['value'];
                });
                sysvar('think-library-config', $config);
            }
            [$type, $field, $outer] = static::_parse($name);
            if (empty($name)) {
                return $config;
            } elseif (isset($config[$type])) {
                $group = $config[$type];
                if ($outer !== 'raw') {
                    foreach ($group as $kk => $vo) {
                        $group[$kk] = htmlspecialchars(strval($vo));
                    }
                }

                return $field ? ($group[$field] ?? $default) : $group;
            } else {
                return $default;
            }
        } catch (\Exception $exception) {
            throw new \Exception($exception->getMessage(), $exception->getCode());
        }
    }

}
